var app = getApp()
var tagsMap = {}

Page({
  data: {
    loaded: false,
    orderId: '',
    orderSource: '',
    commented: false,
    userName: '',
    userPortrait: '',
    rateLevel: null,
    comment: '',
    redPacketInfo: null,
    redBagMoney: 0,
    rewarded: false,
    openRedBag: false,
    rates: [0, 0, 0, 0, 0],
    tags: [],
    commentedTags: [],
    products: []
  },
  onLoad: function (options) {
    wx.hideShareMenu()

    if (!options.orderId) {
      return app.toast.error('参数错误：缺少订单ID')
    }
    if (!options.orderSource) {
      return app.toast.error('参数错误：缺少订单来源')
    }
    this.setData({
      orderId: options.orderId,
      orderSource: options.orderSource
    })
    app.showLoading()
    app.ready(() => {
      this.getCommentInfo()
    })
  },
  onShareAppMessage: function () {
    return {
      title: '只有真朋友才会向你炫耀刚买的原麦山丘',
      path: `/pages/my/evaluate/share?orderId=${this.data.orderId}&userId=${app.globalData.userid}&orderSource=${this.data.orderSource}`,
      imageUrl: '../../imgs/redbag.png'
    }
  },
  getCommentInfo: function () {
    let params = {
      userId: app.globalData.userid,
      orderId: this.data.orderId,
      orderSource: this.data.orderSource
    }
    params = {
      __zaofans: true,
      datas: JSON.stringify(params)
    }
    app.request('/yuanmai_we/comments/get/info', params).then(res => {
      tagsMap = res.tags
      this.setData({
        commented: res.commented,
        userPortrait: res.userPortrait,
        userName: res.userName,
        redBagMoney: res.commented ? res.commentReward.amount : 0,
        rates: res.commented ? this.reduceRates(+res.comment.grade - 1) : this.data.rates,
        rateLevel: res.commented ? +res.comment.grade : null,
        commentedTags: res.commented ? res.comment.tag.split('，') : [],
        comment: res.commented ? res.comment.content : '',
        products: (res.dtls || []).map(item => ({content: '', grade: 0, ...item})),
        loaded: true
      })
    }, err => {
      app.toast.error(err)
    }).finally(app.hideLoading)
  },
  reduceRates: function (index) {
    var rates = this.data.rates.map((item, i) => {
      if (i <= index) {
        return 1
      } else {
        return 0
      }
    })

    return rates
  },
  selectLevel: function (e) {
    if (this.data.commented) return
    var index = +e.currentTarget.dataset.index
    this.setData({
      rates: this.reduceRates(index),
      rateLevel: index + 1,
      tags: tagsMap[index + 1].split('，').map(item => ({name: item, selected: false}))
    })
  },
  selectTag: function (e) {
    var index = e.currentTarget.dataset.index
    var curTag = this.data.tags[index]
    curTag.selected = !curTag.selected
    this.setData({
      tags: this.data.tags
    })
  },
  setComment: function (e) {
    this.setData({
      comment: e.detail.value
    })
  },
  handleGrade: function (e) {
    if (this.data.commented) return
    var data = e.currentTarget.dataset
    var grade = +data.grade
    var index = data.index
    this.data.products[index].grade = grade
    this.setData({
      products: this.data.products
    })
  },
  setProductComment: function (e) {
    var index = e.currentTarget.dataset.index
    this.data.products[index].content = e.detail.value
    this.setData({
      products: this.data.products
    })
  },
  closeRedPacket: function () {
    this.setData({
      openRedBag: false
    })
  },
  openRedPacket: function () {
    this.setData({
      openRedBag: true
    })
  },
  submitComment: function () {
    let errMsg = ''

    if (this.data.rateLevel === null) {
      errMsg = '您还未对商品进行评分哦~~'
    } else if (this.data.comment === '') {
      errMsg = '请点评一下商品哦~~'
    } else if (this.data.comment.length < 7) {
      errMsg = '您的评论不可以少于7个字哦~'
    }

    if (errMsg !== '') {
      return app.toast.error(errMsg)
    }

    let selectedTags = this.data.tags
      .filter(item => item.selected === true)
      .map(item => item.name)
      .join("，")

    let params = {
      userId: app.globalData.userid,
      orderId: this.data.orderId,
      orderSource: this.data.orderSource,
      grade: this.data.rateLevel,
      tag: selectedTags,
      content: this.data.comment,
      commentDtls: this.data.products
    }

    params = {
      __zaofans: true,
      datas: JSON.stringify(params)
    }

    app.showLoading()
    app.request('/yuanmai_we/comments/add', params).then(res => {
      if (res.success) {
        this.setData({
          redPacketInfo: res,
          rewarded: true,
          openRedBag: true
        })
        this.getCommentInfo()
        wx.showShareMenu()
      } else {
        app.toast.error(res.errmsg)
      }
    }, err => {
      app.toast.error(err)
    }).finally(app.hideLoading)
  }
})
